package com.zhao.newcoder.service.impl;

import com.zhao.newcoder.DTO.response.TokenInfo;
import com.zhao.newcoder.service.PermissionService;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.springframework.http.*;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.http.AccessTokenRequiredException;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@Service
public class PermissionServiceImpl implements PermissionService {

    private RestTemplate restTemplate = new RestTemplate();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        return true;
//        TokenInfo token = (TokenInfo) request.getSession().getAttribute("token");
//        if(token==null){
//            System.out.println("token为空");
//            if (authentication instanceof AnonymousAuthenticationToken){
//                throw new AccessTokenRequiredException(null);
//            }
//        }else{
//            if(token.isExpired()) {
//                System.out.println("token过期");
//                String oauthServiceUrl = "https://pa.kobefan.cn/oauth/token";
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//                headers.setBasicAuth("gateway", "123456");
//
//                MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//                params.add("grant_type", "refresh_token");
//                params.add("refresh_token", token.getRefresh_token());
//
//                HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
//
//                try {
//                    ResponseEntity<TokenInfo> newToken = restTemplate.exchange(oauthServiceUrl, HttpMethod.POST, entity, TokenInfo.class);
//                    request.getSession().setAttribute("token", newToken.getBody().init());
//                } catch (Exception e) {
//                    System.out.println("刷新token失败");
//                    request.getSession().removeAttribute("token");
//                    return false;
//                }
//                System.out.println("刷新token成功");
//            }
//        }
//        return true;
    }
}
